package com.redrose.videodemo.activity;

import android.Manifest;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Parcel;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.TextView;

import com.redrose.videodemo.R;
import com.redrose.videodemo.base.BaseActivity;
import com.redrose.videodemo.bean.Person;
import com.redrose.videodemo.bean.VideoVo;
import com.redrose.videodemo.camera.CameraActivity;
import com.redrose.videodemo.okhttpustil.BaseResponed;
import com.redrose.videodemo.okhttpustil.BaseUrl;
import com.redrose.videodemo.okhttpustil.BaseMessage;
import com.redrose.videodemo.okhttpustil.ResponseCallback;
import com.redrose.videodemo.runnabletask.DownloadDouyinVideo;
import com.redrose.videodemo.service.AccessibilitySampleService;
import com.redrose.videodemo.utils.EventBusMessage;
import com.redrose.videodemo.utils.IntentUtils;
import com.redrose.videodemo.utils.LogUtils;
import com.redrose.videodemo.utils.PathUtil;
import com.redrose.videodemo.utils.ThreadTask;
import com.redrose.videodemo.utils.ThreadTask.ThreadPeriod;
import com.redrose.videodemo.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.litepal.crud.DataSupport;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * Desc: app 主界面
 * author: RedRose
 * Date: 2019/3/10
 * Email: yinsxi@163.com
 */
@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    //    @ViewInject(R.id.main_opencamera)
    @ViewInject(R.id.main_opencamera)
    private TextView mOpenCamera;
    @ViewInject(R.id.main_download)
    private TextView mDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] permissoons = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        if (!hasPermission(permissoons[0])) {
            requestPeermission(permissoons, 0);
        }
    }

    @Event(value = {R.id.main_opencamera,
            R.id.main_openimage,
            R.id.main_download,
            R.id.auto_publish,
            R.id.testHttpUtil,
            R.id.learnPlan,
            R.id.testParcelable,
            R.id.readParcelable,
            R.id.getNeedPublish})
    private void onclickView(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.main_opencamera:
                ToastUtil.show(mContext.getApplicationContext(), "open 相机");
                Intent intent = new Intent(mContext, CameraActivity.class);
                startActivity(intent);
                break;
            case R.id.main_openimage:
                IntentUtils.goToImageActivity(mContext, null);
                break;
            case R.id.main_download:
//                downloadVideo();
                break;
            case R.id.testHttpUtil:

                break;
            //获取需要发布的数据
            case R.id.getNeedPublish:
                getNeedPublish();
                break;
            //开始自动发布
            case R.id.auto_publish:
//                List<VideoVo> needPublishList = getLocalNeedPublish();
//                if (needPublishList.size() > 0) {
//
//                    startPublish();
//                } else {
//                    ToastUtil.show(mContext.getApplicationContext(), "请先获取需要发布的数据！");
//                }
                startPublish();
                break;
            case R.id.learnPlan:
                openLearnPlan();
                //将parcelable 对象序列化到磁盘
            case R.id.testParcelable:
                File file = new File(PathUtil.getAppDocPath() + "testParcelable.txt");
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    Person p = new Person(1, "XueQin");
                    FileOutputStream out = (new FileOutputStream(file));
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    Parcel parcel = Parcel.obtain();
                    List<Person> list = new ArrayList<>();
                    list.add(p);
                    parcel.writeParcelable(p,0);
                    bos.write(parcel.marshall());
                    bos.flush();
                    bos.close();
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
                //反序列化parcelable对象
            case R.id.readParcelable:
                try {
                    File file2 = new File(PathUtil.getAppDocPath() + "testParcelable.txt");
                    FileInputStream in = new FileInputStream(file2);
                    byte[] bytes = new byte[in.available()];
                    in.read(bytes);
                    Parcel parcel = Parcel.obtain();
                    parcel.unmarshall(bytes, 0, bytes.length);
                    parcel.setDataPosition(0);
                    Person person = parcel.readParcelable(Thread.currentThread().getContextClassLoader());
                    in.close();
                    LogUtils.e(TAG, person.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private void openLearnPlan() {
        IntentUtils.goToLearnActivity(mContext, null);
    }

    private void startPublish() {
        if (isAccessibilitySettingsOn()) {
            openOtherApp("com.ss.android.ugc.aweme");
//            openOtherApp("com.bly.dkplat");
        } else {
            goAccess();
        }
    }

    private void openOtherApp(String s) {
        PackageManager packageManager = getPackageManager();
        Intent i = packageManager.getLaunchIntentForPackage(s);
        startActivity(i);
    }

    private void openDuoKaiFenShen() {
        openOtherApp("com.bly.dkplat");
    }

    private void getNeedPublish() {
        OkHttpUtils.get().url(BaseUrl.GETNEEDPUBLISH)
                .build().execute(new ResponseCallback<BaseMessage<VideoVo>>() {

            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.d(TAG, e.toString());

            }

            @Override
            public void onResponse(BaseMessage<VideoVo> response, int id) {
                if (response.getCode() == BaseMessage.RESULT_SUCESS) {
                    LogUtils.d(TAG, "VideoBean" + response.toString());
                    List<VideoVo> data = response.getData();
                    int size = data.size();
                    LogUtils.d(TAG, "need publish size" + size);
                    if (size == 0) {
                        ToastUtil.show(mContext.getApplicationContext(), "暂时没有需要发布的数据或已经自动发布完毕");
                    } else {
                        downloadVideo(data.get(0).getVideoUrl());
                    }
                }
            }
        });
    }

    private boolean isNOtExsit(long id) {
        List<VideoVo> videoVos = DataSupport.where("id = ?", String.valueOf(id)).find(VideoVo.class);
        int size = videoVos.size();
        return size == 0;
    }

    private List<VideoVo> getLocalNeedPublish() {
        List<VideoVo> needPublishList = DataSupport.where("isPublish = ?", String.valueOf(0)).find(VideoVo.class);
        return needPublishList;
    }

    private void updateStatues() {
        OkHttpUtils.get().url(BaseUrl.UPDATESTATUTS)
                .addParams("id", "")
                .build().execute(new ResponseCallback<BaseMessage<BaseResponed>>() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(BaseMessage<BaseResponed> response, int id) {

            }
        });
    }

    /**
     * 下载抖音视频
     */
    private void downloadVideo(String needDownload) {
        ThreadTask.getInstance().executorNetThread(new DownloadDouyinVideo(needDownload), ThreadPeriod.PERIOD_MIDDLE);
    }

    private AccessibilityManager mAccessibilityManager;

    /**
     * Check当前辅助服务是否启用
     *
     * @param serviceName serviceName
     * @return 是否启用
     */
    private boolean checkAccessibilityEnabled(String serviceName) {
        mAccessibilityManager = (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
        List<AccessibilityServiceInfo> accessibilityServices =
                mAccessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 前往开启辅助服务界面
     */
    public void goAccess() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    private boolean isAccessibilitySettingsOn() {
        int accessibilityEnabled = 0;
        // TestService为对应的服务
        final String service = getPackageName() + "/" + AccessibilitySampleService.class.getCanonicalName();
        Log.i(TAG, "service:" + service);
        // com.z.buildingaccessibilityservices/android.accessibilityservice.AccessibilityService
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
            Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            // com.z.buildingaccessibilityservices/com.z.buildingaccessibilityservices.TestService
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e(TAG, "--MainActivity---");
    }

    @Override
    public void onEventBusMessageRecieved(EventBusMessage message) {
        super.onEventBusMessageRecieved(message);
        int id = message.getId();
        switch (id) {
            //抖音视频下载结束
            case EventBusMessage.MSG_TYPE_GET_DOUYIN_DOWNLOAD_FINSH:
                startPublish();
                break;
            //发布上一段抖音视频完毕
            case EventBusMessage.MSG_TYPE_GET_NEED_PUBLISH:
                getNeedPublish();
                break;
            default:
                break;
        }
    }
}